<template>
  <div v-loading="loading" class="bill-detail">
    <el-dialog v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.2)" :visible.sync="dialogShow" title="变更开单明细" :close-on-click-modal="false" @opened="handleBack" @close="closeHandle">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="90px">
        <el-form-item prop="reason" label="订单号:">
          <table-box
            ref="orderCodeTable"
            :off-set="-20"
            :data="tableData"
            :table-config="tableConfig"
            :table-max-height="200"
            @btnOperate="btnOperate"
          >
            <!-- <el-table-column prop="poCode" label="采购订单号" sortable min-width="100">
              <template slot-scope="scope">
                <el-input ref="materialInput" v-model.trim="scope.row.poCode" onkeyup="value=value.replace(/[^a-zA-Z0-9]/g,'')" size="mini" placeholder="请输入采购订单号" maxlength="128" @change="checkDetailItemPo(scope.row)" />
              </template>
            </el-table-column> -->
            <el-table-column prop="soCode" label="销售订单号" sortable min-width="100">
              <template slot-scope="scope">
                <el-input ref="materialInput" v-model.trim="scope.row.soCode" onkeyup="value=value.replace(/[^a-zA-Z0-9]/g,'')" size="mini" placeholder="请输入销售订单号" maxlength="128" @change="checkDetailItemSo(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column prop="orderDesc" label="说明" sortable min-width="100">
              <template slot-scope="scope">
                <el-input ref="materialInput" v-model.trim="scope.row.orderDesc" size="mini" placeholder="请输入说明" maxlength="128" />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </table-box>
          <!-- <c-table-box :table-max-height="200" :data="formData.orderCodes" :index="false" :table-config="tableConfig" /> -->
        </el-form-item>
        <el-form-item label="开单明细附件:">
          <div v-for="item in fileTypeList" :key="item.id">
            <div class="qup-title-box">
              <span class="border" /><span>附件上传-{{ item.attachmentType }}</span>
            </div>
            <file-uploader
              :data="item.fileList"
              :file-type="item.fileTypeName"
              :config-attachment-id="item.id"
              :limit="20"
              @remove="removeFile"
              @upload-success="uploadSuccessFile"
            />
          </div>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="confirmHandle">确定</el-button>
          <el-button type="primary" @click="handleBack">取消</el-button>
        </el-form-item> -->
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="handleBack">取消</el-button>
        <el-button type="primary" size="mini" @click="confirmHandle">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { postConfigAttachmentTemplate, getProConfigEditData, changeFileList, changeConfigState } from '@/api/proConfig'
// import { getDictByPatchType } from '@/api/dataDict'
import fileUploader from '@/components/importFile'
import { getShopAttachment } from '@/api/decorate'
export default {
  name: 'BillDetail',
  components: {
    fileUploader
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      fileTypeList: [],
      formData: {
        orderCodes: [],
        accessory: ''
      },
      formRules: {},
      tableData: [],
      tableConfig: {
        hideSearchBar: true,
        setting: [],
        btnList: [{
          buttonName: '新增',
          optCode: 'add',
          outerFlag: true
        }]
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  async created() {
    this.formData.id = this.detailData.id
    await getProConfigEditData(this.formData.id).then(res => {
      if (res.success && res.data) {
        this.formData = res.data
        this.tableData = this.formData.productConfigOrderDtos
      }
    })
    await postConfigAttachmentTemplate('PRODUCT_CONFIG').then(res => {
      if (res.success === 1) {
        // 根据modelId获取每个配置id
        if (res.data && res.data.records) {
          this.fileTypeList = res.data.records.filter(item => item.attachmentType === '开单明细附件')
          this.fileTypeList.forEach(row => {
            this.$set(row, 'fileList', [])
          })
        }
        this.getFiles()
      }
    })
  },
  methods: {
    // 获取附件
    getFiles() {
      getShopAttachment(this.formData.id).then(res => {
        this.fileTypeList.forEach(row => {
          row.fileList = res.data.filter(i => i.configAttachmentId === row.id)
        })
      })
    },
    removeFile() {},
    uploadSuccessFile() {},
    // 按钮组
    btnOperate(flag) {
      switch (flag) {
        case 'add':
          this.addRow()
          break
        default:
          break
      }
    },
    // checkDetailItemPo(row) {
    //   const poCode = row.poCode
    //   const soCode = row.soCode
    //   const flag = this.tableData.filter(item => ((item.poCode.length && item.poCode === poCode) && (item.soCode.length && item.soCode === soCode)))
    //   if (flag.length > 1) {
    //     this.$message.warning(`销售订单号${soCode}对应的采购订单号${poCode}已存在，请重新输入`)
    //     row.poCode = ''
    //   }
    // },
    checkDetailItemSo(row) {
      const poCode = row.poCode
      const soCode = row.soCode
      const flag = this.tableData.filter(item => ((item.poCode.length && item.poCode === poCode) && (item.soCode.length && item.soCode === soCode)))
      if (flag.length > 1) {
        this.$message.warning(`采购订单号${poCode}对应的销售订单号${soCode}已存在，请重新输入`)
        row.soCode = ''
      }
    },
    // 删除
    handleDel(row) {
      const index = this.tableData.findIndex(item => (item.poCode === row.poCode && item.soCode === row.soCode))
      if (index !== -1) {
        this.tableData.splice(index, 1)
      }
    },
    // 返回
    handleBack() {
      this.dialogShow = false
      this.clearForm()
      this.$emit('success')
    },
    clearForm(done) {
      this.formData = {
        constData: [],
        staff: []
      }
      this.$refs.rulesForm && this.$refs.rulesForm.clearValidate()
      done && done()
    },
    // 确认
    confirmHandle() {
      this.$refs.form.validate(validate => {
        if (validate) {
          const len = this.fileTypeList.map(item => item.fileList.length)
          if (this.formData.demandResultHandle === 'ORDER_SUCC') {
            if (!len[0]) {
              this.$message.warning('请至少上传一个开单明细附件')
              return
            }
          }
          this.loading = true
          const dtos = this.fileTypeList.map(item => item.fileList)
          dtos[0].forEach(file => {
            file.modelId = this.formData.id
          })
          changeFileList(dtos[0], this.formData.id).then(res => {
            if (res.success) {
              // this.$message.success('附件上传成功')
              changeConfigState(this.formData).then(res => {
                if (res.success) {
                  this.$message.success('操作成功')
                  this.clearForm()
                  this.dialogShow = false
                  this.$emit('success', false)
                }
              })
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    removeRow(row) {
      this.formData.orderCodes.splice(row.keyIndex, 1)
    },
    addRow() {
      this.tableData.push({
        poCode: '',
        soCode: ''
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.bill-detail{
  display: inline-block;
  margin: 0 10px;
}
/deep/.el-table{
  max-height: 200px;
}
</style>
